2
2
.
.
3
3
.
.
1
1
C
C
o
o
n
n
s
s
t
t
a
a
n
n
t
t
s
s
I
I
n
n
f
f
o
o
Constant has value which cannot be changed once it is set (unlike Variable which can change its value multiple times)
Referencing Constant that has no Value gives error: the local variable 'age' might not habe been initialized.
This is because only Optional Constants are allowed to be null. This is why Optionals were introduced in the first place to
detect these kind of errors at compile time rather than during run time.
C
C
o
o
n
n
s
s
t
t
a
a
n
n
t
t
S
S
y
y
n
n
t
t
a
a
x
x
Constant is declared by
using required Keyword final final
followed by required Constant's Data Type String
followed by required Constant's Name name
followed by optional Constant's Value "John" (can be set later once if not during declaration)
E
E
x
x
a
a
m
m
p
p
l
l
e
e
In this example we declare
Constant name by specifying Data Type as String and by giving it an initial value of "John"
Constant age by specifying only Data Type as int
Constant Syntax
//DECLARE CONSTANT.
final String name = "John"; //Full Syntax with both Data Type and initial value
final int age; //Only Data Type without initial value
//ASSIGN NEW VALUE TO CONSTANT.
age = 20; //Constant's value can be set only once
//age = 30; //This line would throw error since we are trying to change value of a
Constant
//DISPLAY CONSTANT.
System.out.println(age);